package sd.czw.com.mmgapp.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;
import com.zhy.http.okhttp.OkHttpUtils;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import sd.czw.com.mmgapp.Contants;
import sd.czw.com.mmgapp.R;
import sd.czw.com.mmgapp.activity.CompanyActiviy;
import sd.czw.com.mmgapp.activity.LoginActivity;
import sd.czw.com.mmgapp.activity.RzImageActivity;
import sd.czw.com.mmgapp.activity.TGActivity;
import sd.czw.com.mmgapp.activity.WantToRzActivity;
import sd.czw.com.mmgapp.adapter.PinpaiRvAdapter;
import sd.czw.com.mmgapp.adapter.RuzhuRvAdapter;
import sd.czw.com.mmgapp.adapter.SyRvAdapter;
import sd.czw.com.mmgapp.mcallback.HomeGoodsCallback;
import sd.czw.com.mmgapp.mcallback.MyHomeCallback;
import sd.czw.com.mmgapp.model.shouyebean.HomeGoodsInfo;
import sd.czw.com.mmgapp.model.shouyebean.HomeInfo;
import sd.czw.com.mmgapp.utils.SpUtils;

import android.os.Handler;

/**
 * Created by czw
 * desc 描述：首页
 * on 2017/7/5.
 */
public class ShouyeFragment extends Fragment implements View.OnClickListener {
    private View rootView;
    private List<String> urls = new ArrayList<>();
    private Banner topbanner;
    private RelativeLayout rl_tm,rl_rz,rl_tg,rl_jj;
    private ImageView banner_bottom_image,img_left,img_top,img_bottom,rz_img;
    private RecyclerView pprv,rzrv;
    private HomeInfo.ErrmsgBean errmsg;
    private int start = 0;
    public static final int limit = 20;
    private int page = 0;
    private SyRvAdapter syRvAdapter;
    private List<HomeGoodsInfo.ErrmsgBean> goodsdatas = new ArrayList<>();
    private GridLayoutManager rmanager;
    private RecyclerView syrv;
    private MaterialRefreshLayout refresh;
    private boolean isLoadMore = true;
    private String token;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_shouye, container, false);
        System.out.println("time:"+Contants.Time);
        System.out.println("sign:"+Contants.Sign);
        //获取控件
        initviews();
        //请求数据
        getdatas();
        //获取商品列表数据
        getgoodsdatas(start);
        //商品列表
        setgoodsrv(goodsdatas);
        //刷新 加载更多
        refreshandloadmore();
        //各模块点击事件
        setuplistener();
        return rootView;
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //品牌特卖
            case R.id.rl_tm:
                break;
            //我要入驻
            case R.id.rl_rz:
                token = SpUtils.setToken(getContext()).getString("token","");
                if (token != null && !("".equals(token))){
                    startOtherActivity(WantToRzActivity.class);
                }else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("flag","rl_rz");
                    startActivity(intent);
                }
                break;
            //我的推广
            case R.id.rl_tg:
                token = SpUtils.setToken(getContext()).getString("token","");
                if (token != null && !("".equals(token))){
                    startOtherActivity(TGActivity.class);
                }else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("flag","rl_tg");
                    startActivity(intent);
                }
                break;
            //公司简介
            case R.id.rl_jj:
                startOtherActivity(CompanyActiviy.class);
                break;
            /**
             * 入驻专区  图片的点击事件
             */
            case R.id.rz_img:
                break;
            case R.id.img_left:
                startRzImageActivity(RzImageActivity.class,errmsg.getImg().getZhongjian_img().get(0).getId()+"",errmsg.getImg().getZhongjian_img().get(0).getTitle(),errmsg.getImg().getZhongjian_img().get(0).getImg());
                break;
            case R.id.img_top:
                startRzImageActivity(RzImageActivity.class,errmsg.getImg().getZhongjian_img().get(1).getId()+"",errmsg.getImg().getZhongjian_img().get(1).getTitle(),errmsg.getImg().getZhongjian_img().get(1).getImg());
                break;
            case R.id.img_bottom:
                startRzImageActivity(RzImageActivity.class,errmsg.getImg().getZhongjian_img().get(2).getId()+"",errmsg.getImg().getZhongjian_img().get(2).getTitle(),errmsg.getImg().getZhongjian_img().get(2).getImg());
                break;

        }
    }

    private void startOtherActivity(Class c){
        Intent intent = new Intent(getActivity(), c);
        startActivity(intent);
    }

    private void startRzImageActivity(Class c,String id,String title,String path){
        Intent intent = new Intent(getActivity(), c);
        intent.putExtra("id",id);
        intent.putExtra("title",title);
        intent.putExtra("path",path);
        startActivity(intent);
    }
    /**
     * 点击事件
     */
    private void setuplistener() {
        rl_tm.setOnClickListener(this);
        rl_rz.setOnClickListener(this);
        rl_tg.setOnClickListener(this);
        rl_jj.setOnClickListener(this);
        rz_img.setOnClickListener(this);
        img_left.setOnClickListener(this);
        img_top.setOnClickListener(this);
        img_bottom.setOnClickListener(this);
    }

    /**
     * 刷新、加载更多
     */
    private void refreshandloadmore() {
        refresh = (MaterialRefreshLayout) rootView.findViewById(R.id.refresh);
        refresh.setSunStyle(true);
        refresh.setIsOverLay(true);
        refresh.setWaveShow(false);
        refresh.setLoadMore(isLoadMore);
        refresh.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       // getdatas();
                        refresh.finishRefresh();
                    }
                },1000);
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isLoadMore = false;
                        page++;
                        start = 20*page;
                        getgoodsdatas(start);
                        syRvAdapter.notifyDataSetChanged();
                        refresh.finishRefreshLoadMore();
                    }
                }, 500);
            }
        });
        //自动刷新
        if (goodsdatas != null){
            refresh.autoRefresh();
        }
    }

    //获取商品列表数据
    private void getgoodsdatas(int n) {
        OkHttpUtils.post().url(Contants.HOME_GOODSLIST).addParams("start", String.valueOf(n)).addParams("limit", String.valueOf(limit))
                .addParams("time",Contants.Time).addParams("sign",Contants.Sign).build()
                .execute(new HomeGoodsCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(HomeGoodsInfo response, int id) {
                        if (response.getErrcode() == 1){
                            List<HomeGoodsInfo.ErrmsgBean> errmsg = response.getErrmsg();
                            goodsdatas.addAll(errmsg);
                            syRvAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    //商品列表
    private void setgoodsrv(List<HomeGoodsInfo.ErrmsgBean> goodsdatas) {
        syRvAdapter = new SyRvAdapter(getContext(), this.goodsdatas,getActivity().getWindowManager().getDefaultDisplay().getWidth());
        syrv.setAdapter(syRvAdapter);

    }

    //顶部轮播图
    private void setbannerimage(HomeInfo.ErrmsgBean errmsg) {
        for (int i = 0;i < errmsg.getImg().getAdv_img().size();i++){
            urls.add(errmsg.getImg().getAdv_img().get(i).getUrl());
        }
        topbanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setIndicatorGravity(BannerConfig.RIGHT)
                .setImages(urls)
                .setDelayTime(3000)
                .setImageLoader(new GlideImageLoader())
                .start();
    }
    //请求网络数据
    private void getdatas() {
        OkHttpUtils.post().url(Contants.HOME_URL).addParams("time", Contants.Time).addParams("sign", Contants.Sign)
                .build().execute(new MyHomeCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(getContext(), "网络.丢失了", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(HomeInfo response, int id) {
                if (response.getErrcode() == 1) {
                    errmsg = response.getErrmsg();
                    setbannerimage(errmsg);
                    setstaticimage(errmsg);
                    setpprv(errmsg);
                    setrzrv(errmsg);
                }else {
                    Toast.makeText(getContext(), ""+response.getErrmsg(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //入驻列表
    private void setrzrv(HomeInfo.ErrmsgBean errmsg) {
        List<HomeInfo.ErrmsgBean.CatImgBean> cat_img = errmsg.getCat_img();
        RuzhuRvAdapter ruzhuRvAdapter = new RuzhuRvAdapter(getContext(), cat_img);
        rzrv.setAdapter(ruzhuRvAdapter);
    }
    //品牌列表
    private void setpprv(HomeInfo.ErrmsgBean errmsg) {
        List<HomeInfo.ErrmsgBean.ImgBean.PinpaiImgBean> pinpai_img = errmsg.getImg().getPinpai_img();
        PinpaiRvAdapter pinpaiRvAdapter = new PinpaiRvAdapter(getContext(), errmsg.getImg().getPinpai_img());
        pprv.setAdapter(pinpaiRvAdapter);
    }
    //静态图片展示
    private void setstaticimage(HomeInfo.ErrmsgBean errmsg) {
        Glide.with(getContext()).load(errmsg.getImg().getLibao_img()).placeholder(new ColorDrawable(Color.parseColor("#f5f5f5"))).into(banner_bottom_image);
        Glide.with(getContext()).load(errmsg.getImg().getRuzhu_img()).placeholder(new ColorDrawable(Color.parseColor("#f5f5f5"))).into(rz_img);
//        Glide.with(getContext()).load(errmsg.getImg().getZhongjian_img().get(0).getUrl()).placeholder(new ColorDrawable(Color.parseColor("#f5f5f5"))).into(img_left);
//        Glide.with(getContext()).load(errmsg.getImg().getZhongjian_img().get(1).getUrl()).placeholder(new ColorDrawable(Color.parseColor("#f5f5f5"))).into(img_top);
//        Glide.with(getContext()).load(errmsg.getImg().getZhongjian_img().get(2).getUrl()).placeholder(new ColorDrawable(Color.parseColor("#f5f5f5"))).into(img_bottom);
    }

    //获取控件
    private void initviews() {
        //头部
        View topviews = rootView.findViewById(R.id.layout_banner);
        topbanner = (Banner) topviews.findViewById(R.id.top_banner);//头部轮播图
        rl_tm = (RelativeLayout) topviews.findViewById(R.id.rl_tm);//品牌特卖
        rl_rz = (RelativeLayout) topviews.findViewById(R.id.rl_rz);//我要入驻
        rl_tg = (RelativeLayout) topviews.findViewById(R.id.rl_tg);//我的推广
        rl_jj = (RelativeLayout) topviews.findViewById(R.id.rl_jj);//公司简介
        banner_bottom_image = (ImageView) topviews.findViewById(R.id.banner_bottom_img);

        //品牌专区
        View ppviews = rootView.findViewById(R.id.layout_pp);
        pprv = (RecyclerView) ppviews.findViewById(R.id.ppzq_rv);
        LinearLayoutManager manager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
        pprv.setLayoutManager(manager);

        //入驻专区
        View rzviews = rootView.findViewById(R.id.layout_rz);
        rz_img = (ImageView) rzviews.findViewById(R.id.rz_img);
        img_left = (ImageView) rzviews.findViewById(R.id.img_left);
        img_top = (ImageView) rzviews.findViewById(R.id.img_top);
        img_bottom = (ImageView) rzviews.findViewById(R.id.img_bottom);
        rzrv = (RecyclerView) rzviews.findViewById(R.id.rzrv);
        GridLayoutManager gmanager =new GridLayoutManager(getContext(),4,LinearLayoutManager.VERTICAL,false);
        rzrv.setLayoutManager(gmanager);

        //热卖产品
        View rmviews = rootView.findViewById(R.id.layout_rm);
        syrv = (RecyclerView) rmviews.findViewById(R.id.syrv);
        rmanager = new GridLayoutManager(getContext(),2,LinearLayoutManager.VERTICAL,false);
        syrv.setLayoutManager(rmanager);
        syrv.setHasFixedSize(true);
        syrv.setNestedScrollingEnabled(false);
    }


    //将头部轮播图url传入布局中
    class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //下载图片
            Glide.with(context).load(path).into(imageView);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        topbanner.stopAutoPlay();
    }
}
